<script lang="ts" setup>
import * as echarts from 'echarts';
import { onMounted, ref, watch } from 'vue';
import { message } from 'ant-design-vue';
import type { ECharts } from 'echarts';
import { useDownExcel } from './useDownExcel';
// 按考核项目
const data = ref<any[]>([]);
const loading = ref<boolean>(false);
const dataIsReady = ref(false);
const radarChartRef = ref<HTMLElement | null>(null);
let radarChart: ECharts | null = null;

// 假设 getdiagramData 是一个定义在外部的函数，用于获取数据
async function getAlldiagramData() {
  data.value = [];
  loading.value = true;
  await getdiagramData().then((res: any) => {
    data.value = res.data;
    dataIsReady.value = true;
    if (res) {
      data.value = res.data;
      // eslint-disable-next-line no-console
      console.log(data.value);
      dataIsReady.value = true;
    }
  }).catch(() => {
    message.error('数据获取失败！');
  }).finally(() => {
    loading.value = false;
  });
}

function initRadarChart() {
  if (radarChartRef.value) {
    radarChart = echarts.init(radarChartRef.value);
    watch(dataIsReady, (newVal) => {
      if (newVal) {
        updateRadarChart();
      }
    });
  }
}

function updateRadarChart() {
  if (!radarChart || !dataIsReady.value || !data.value) {
    return;
  }
  const regions = ['越城', '柯桥', '上虞', '嵊州', '新昌', '诸暨'];
  data.value.forEach((module) => {
    const indicators = regions.map(region => ({
      name: region,
      max: Number.parseFloat(module.mainIndicatorScore),
    }));

    const option: any = {
      title: {
        text: module.evaluationItem,
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold',
          color: '#333',
        },
        padding: [20, 20, 20, 20],
      },
      tooltip: {},
      legend: {
        data: [module.evaluationItem],
        top: '4%',
        right: '5%',
      },
      radar: {
        name: {
          textStyle: {
            color: 'black',
            backgroundColor: 'white',
            borderRadius: 3,
            fontSize: 16,
          },
        },
        indicator: indicators,
        center: ['50%', '55%'],
        splitLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.5)',
          },
        },
        splitArea: {
          areaStyle: {
            color: ['rgba(114, 172, 209, 0.2)', 'rgba(114, 172, 209, 0.4)', 'rgba(114, 172, 209, 0.6)', 'rgba(114, 172, 209, 0.8)', 'rgba(114, 172, 209, 1)'],
          },
        },
      },
      series: [{
        type: 'radar',
        data: [{
          value: [module.yuecheng, module.keqiao, module.shangyu, module.shengzhou, module.xinchang, module.zhuji].filter(Number) as number[],
          name: module.evaluationItem,
        }],
      }],
    };

    const chartContainer = document.createElement('div');
    chartContainer.style.width = '600px';
    chartContainer.style.height = '400px';
    chartContainer.style.marginBottom = '50px';
    document?.querySelector('#radarChartsContainer')?.appendChild(chartContainer);

    const singleRadarChart = echarts.init(chartContainer);
    singleRadarChart.setOption(option);
    chartContainer.addEventListener('click', () => {
      downloadChart(chartContainer, module.evaluationItem);
    });
  });
}

function downloadChart(container: HTMLElement, filename: string) {
  const chart = echarts.init(container);
  const url = chart.getDataURL({
    type: 'png',
    pixelRatio: 2,
    backgroundColor: '#fff',
  });
  const link = document.createElement('a');
  link.download = filename;
  link.href = url;
  link.click();
}
function downloadAllCharts() {
  const containers = document.querySelectorAll('#radarChartsContainer > div');
  const containers2 = document.querySelectorAll('#radarChartsContainer2 > div');

  containers.forEach((container) => {
    const filename: any = (container as HTMLElement).dataset.filename;
    downloadChart(container as HTMLElement, filename);
  });
  containers2.forEach((container) => {
    const filename: any = (container as HTMLElement).dataset.filename;
    downloadChart(container as HTMLElement, filename);
  });
}

// 按区域
const data2 = ref<any[]>([]);
const loading2 = ref<boolean>(false);
const dataIsReady2 = ref(false);
const radarChartRef2 = ref<HTMLElement | null>(null);
let radarChart2: ECharts | null = null;

// 假设 getdiagramData 是一个定义在外部的函数，用于获取数据
async function getAlldiagramData2() {
  data2.value = [];
  loading2.value = true;
  await getdiagramData().then((res: any) => {
    data2.value = res.data;
    dataIsReady2.value = true;
    if (res) {
      data2.value = res.data;
      dataIsReady2.value = true;
    }
  }).catch(() => {
    message.error('数据获取失败！');
  })
    .finally(() => {
      loading2.value = false;
    });
}

function initRadarChart2() {
  if (radarChartRef2.value) {
    radarChart2 = echarts.init(radarChartRef2.value);
    watch(dataIsReady2, (newVal) => {
      if (newVal) {
        updateRadarChart2();
      }
    });
  }
}

function updateRadarChart2() {
  if (!radarChart2 || !dataIsReady2.value || !data2.value) {
    return;
  }
  const regions2 = ['yuecheng', 'keqiao', 'shangyu', 'shengzhou', 'xinchang', 'zhuji'];
  const regionNames2 = ['越城', '柯桥', '上虞', '嵊州', '新昌', '诸暨'];

  // 处理每个地区的数据
  regions2.forEach((region, index) => {
    const regionData: number[] = [];
    const indicators: { name: string, max: number }[] = [];

    data2.value.forEach((module) => {
      const score = Number(module[region]);
      regionData.push(Number.isNaN(score) ? 0 : score); // 保证分数有效
      indicators.push({
        name: module.evaluationItem,
        max: Number.parseFloat(module.mainIndicatorScore),
      });
    });

    const option2: any = {
      title: {
        text: `${regionNames2[index]} 雷达图`,
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold',
          color: '#333',
        },
      },
      tooltip: {},
      legend: {
        data: [regionNames2[index]],
        top: '4%',
        right: '5%',
      },
      radar: {
        name: {
          textStyle: {
            color: 'black',
            fontSize: 16,
          },
        },
        indicator: indicators,
        center: ['50%', '55%'],
        splitLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.5)',
          },
        },
        splitArea: {
          areaStyle: {
            color: ['rgba(114, 172, 209, 0.2)', 'rgba(114, 172, 209, 0.4)'],
          },
        },
      },
      series: [{
        type: 'radar',
        data: [{
          value: regionData,
          name: regionNames2[index],
        }],
      }],
    };

    // 创建图表容器并初始化
    const chartContainer2 = document.createElement('div');
    chartContainer2.style.width = '600px';
    chartContainer2.style.height = '400px';
    chartContainer2.style.marginBottom = '50px';
    document?.querySelector('#radarChartsContainer2')?.appendChild(chartContainer2);
    const singleRadarChart = echarts.init(chartContainer2);
    singleRadarChart.setOption(option2);
    chartContainer2.addEventListener('click', () => {
      downloadChart(chartContainer2, regionNames2[index]);
    });
  });
}

onMounted(() => {
  getAlldiagramData();
  initRadarChart();
  getAlldiagramData2();
  initRadarChart2();
});
const useExcel = useDownExcel();
</script>

<template>
  <PubPageMain class="max">
    <div class="header">
      <div class="left">
        <a-space>
          <div class="pjTitle">
            分析图
          </div>
        </a-space>
      </div>
      <div class="right">
        <a-space>
          <a-button type="primary" @click="downloadAllCharts">
            下载所有雷达图
          </a-button>
          <a-button type="primary" @click="useExcel.downExportWord1()">
            导出word
          </a-button>
          <a-button type="primary" @click="useExcel.downExportWord()">
            导出雷达word
          </a-button>
        </a-space>
      </div>
    </div>
    <div class="content">
      <div>
        <div class="header">
          <div class="left">
            <a-space>
              <div>
                按考核项目
              </div>
            </a-space>
          </div>
        </div>
        <div id="radarChartsContainer" class="radar-charts-container">
          <div ref="radarChartRef" />
        </div>
      </div>
      <a-divider />
      <div>
        <div class="header">
          <div class="left">
            <a-space>
              <div>
                按区县
              </div>
            </a-space>
          </div>
        </div>
      </div>
      <div id="radarChartsContainer2" class="radar-charts-container2">
        <div ref="radarChartRef2" />
      </div>
    </div>
  </PubPageMain>
</template>

<style lang="scss" scoped>
.content {
  box-sizing: border-box;
  display: flex;
  flex: 1;
  flex-direction: column;
  width: 100%;
  height: 95%;
  overflow: auto;
  overflow-y: auto;
}

.radar-charts-container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.radar-charts-container2 {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.radar-chart-container {
  width: 600px;
  height: 400px;
  margin: 10px;
}

.max {
  display: flex;
  flex-direction: column;
  max-width: 100%;
  max-height: 95%;
  overflow: auto;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 31px;
    margin-bottom: 10px;

    .pjTitle {
      padding-left: 15px;
      background: url("@/assets/images/title-left-bg.svg") no-repeat;
    }

    .right {
      display: flex;
      align-items: center;
    }

    .content {
      height: 100%;
      overflow: auto;
    }
  }
}
</style>
